package com.example.thread.d2取钱案例同步代码块;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class Account {
    private String cardId;
    private double money;
    // 所有线程调用静态方法，要用唯一字节码来锁所有的线程，保证唯一
    public static void test() {
        synchronized (Account.class) {

        }
    }
    public Account(String cardId,double money) {
        this.cardId = cardId;
        this.money = money;
    }
    // 小明，小红同时来取钱
    public void drawMoney(double money) {
        // 先搞清楚谁来取钱
        String name = Thread.currentThread().getName();
        // 取钱
        synchronized (this) {
            if(this.money >= money) {
                System.out.println(name+"取钱："+money+"成功");
                this.money -= money;
                System.out.println(name+"来取钱后，余额剩余："+this.money);
            } else {
                System.out.println(name+"来取钱，余额不足！");
            }
        }
    }
}
